#include <zmq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void *reciever, *context;

char * strRecv(void * reciever)
{
	int size;
	char * temp;

	zmq_msg_t msg;
	zmq_msg_init(&msg);
	zmq_recv(reciever, &msg, 0);
	size = zmq_msg_size(&msg);
	temp = malloc(size + sizeof(char));
	memcpy(temp, zmq_msg_data(&msg), size);
	temp[size] = '\0';
	zmq_msg_close(&msg);
	return temp;
}

void strSend(void * reciever, char * text)
{
	zmq_msg_t msg;
	zmq_msg_init_size(&msg, strlen(text));
	memcpy(zmq_msg_data(&msg), text, strlen(text));
	zmq_send(reciever, &msg, 0);
	zmq_msg_close(&msg);
}

int main (int argc, char ** argv)
{
	char * text;

	if (argc < 2)
	{
		printf("To few args\n");
		exit(1);
	}
	text = malloc(sizeof(char));

	if (!(context = zmq_init(1)))
	{
		printf("zmq_init failed");
		return 1;
	}
	
	if (!(reciever = zmq_socket(context, ZMQ_REP)))
	{
		printf("zmq_socket failed");
		zmq_term(context);
		return 1;
	}
	if (zmq_bind(reciever, "tcp://*:5557"))
	{
		printf ("zmq_bind failled");
		zmq_close(reciever);
		zmq_term(context);
		return 1;
	}
	
	for (*text='\0'; strcmp(text, "quit");)
	{
		free(text);
		text = strRecv(reciever);
		printf("%s\n", text);
		strSend(reciever, text);
	}

	free(text);
	zmq_close(reciever);
	zmq_term(context);
	return 0;
}

